/**   
* @Title: DesignPatternConfigController.java
* @Package cn.edu.sjtu.se.dslab.controller
* @Description: define the class DesignPatternConfigController
* @author longshaohang
* @date 2013-7-24 下午11:48:37
* @version V1.0
*/ 
package cn.edu.sjtu.se.dslab.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.edu.sjtu.se.dslab.component.data.AvionicsEquipment;
import cn.edu.sjtu.se.dslab.component.data.DomainEntity;
import cn.edu.sjtu.se.dslab.component.dp.parse.DesignPatternInstanceBean;
import cn.edu.sjtu.se.dslab.component.dp.parse.Property;
import cn.edu.sjtu.se.dslab.component.method.InterfaceMethod;
import cn.edu.sjtu.se.dslab.component.method.MethodComponent;
import cn.edu.sjtu.se.dslab.exception.DBException;
import cn.edu.sjtu.se.dslab.project.BusZone;
import cn.edu.sjtu.se.dslab.service.IAvionicsEquipmentService;
import cn.edu.sjtu.se.dslab.service.IBusZoneService;
import cn.edu.sjtu.se.dslab.service.IDesignPatternComponentService;
import cn.edu.sjtu.se.dslab.service.IDomainEntityService;
import cn.edu.sjtu.se.dslab.service.IEquipmentCategoryService;
import cn.edu.sjtu.se.dslab.service.IInterfaceMethodService;
import cn.edu.sjtu.se.dslab.service.IMethodComponentService;

/** 
 * @ClassName: DesignPatternConfigController
 * @Description: 用于控制配置设计模式组件的页面
 * @author longshaohang
 * @date 2013-7-24 下午11:48:37
 * 
 */
@Controller
public class BusDpConfigController {
	private static final Logger logger = Logger.getLogger(BusDpConfigController.class);
	
	@Resource(name="domainEntityService")
	IDomainEntityService domainEntityService;
	
	@Resource(name="avionicsEquipmentService")
	IAvionicsEquipmentService avionicsEquipmentService;
	
	@Resource(name="equipmentCategoryService")
	IEquipmentCategoryService equipmentCategoryService;
	
	@Resource(name="interfaceMethodService")
	IInterfaceMethodService interfaceMethodService;
	
	@Resource(name="designPatternComponentService")
	IDesignPatternComponentService designPatternComponentService;
	
	@Resource(name="methodComponentService")
	IMethodComponentService methodComponentService;
	
	@Resource(name="busZoneService")
	IBusZoneService busZoneService;
	
	@RequestMapping(value = "/busDesignPattern/{type}/add", method = RequestMethod.POST)
	public String addMethodComponent(@PathVariable(value="type") String type,
			@RequestParam String equipment, @RequestParam String bus_type,
			@RequestParam String bus_zone,
			@RequestParam String equipment_number,
			@RequestParam String read_bus_processing_method, //@RequestParam String read_frequency,
			@RequestParam String read_bus_init_method, @RequestParam String write_bus_init_method,
			@RequestParam String write_bus_processing_method, //@RequestParam String write_frequency,
			@RequestParam String dpcUri, @RequestParam long projectId ){
		Map<String, String> propertyMap = new HashMap<String, String>();
		propertyMap.put("equipment", equipment);
		propertyMap.put("bus_type", bus_type);
		//propertyMap.put("bus_data_area", bus_data_area);
		//propertyMap.put("entity_data_area", entity_data_area);
		propertyMap.put("bus_zone", bus_zone);
		propertyMap.put("equipment_number", equipment_number);
		propertyMap.put("read_bus_processing_method", read_bus_processing_method);
		propertyMap.put("read_bus_init_method", read_bus_init_method);
		//propertyMap.put("read_frequency", read_frequency);
		propertyMap.put("write_bus_processing_method", write_bus_processing_method);
		propertyMap.put("write_bus_init_method", write_bus_init_method);
		//propertyMap.put("write_frequency", write_frequency);
		designPatternComponentService.addDpcItem(propertyMap, dpcUri);
		
		return toURL(type, projectId);
	}
	
	@RequestMapping(value = "/busDesignPattern/delete", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, String> deleteMethodComponent(@RequestParam String name, @RequestParam String equipmentUri, 
			@RequestParam String dpcUri){
		Map<String, String> responseMap = new HashMap<String,String>();
		try{
			designPatternComponentService.deleteDpcItem(name, equipmentUri, dpcUri);
		//if (result){
			responseMap.put("result", Boolean.TRUE.toString());
		//}else{
		//	responseMap.put("result", Boolean.FALSE.toString());
		//}
		}catch(Exception ex){
			responseMap.put("result", Boolean.TRUE.toString());
		}
		return responseMap;
	}
	
	@RequestMapping(value = "/busDesignPattern/info", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, String> getDesignPatternComponentPropertyInfo(@RequestBody Map<String, String> jsonStrings){
		DesignPatternInstanceBean dpiBean = designPatternComponentService.getDesignPatternInstanceBean(jsonStrings.get("dpcUri"));
		
		Map<String, Property> instance = dpiBean.getInstanceByName(
				jsonStrings.get("name"), jsonStrings.get("equipmentUri"));
		Map<String, String> equipmentMap = new HashMap<String, String>();
		//equipment info
		AvionicsEquipment outterEquipment = avionicsEquipmentService.getAvionicsEquipmentByUri(instance.get("equipment").getValue());
		equipmentMap.put("equipment_info", outterEquipment.getName());
		//bus type
		AvionicsEquipment busType = avionicsEquipmentService.getAvionicsEquipmentByUri(instance.get("bus_type").getValue());
		equipmentMap.put("bus_type_info", busType.getName());
		//bus zone
		long busZoneId = Long.parseLong(instance.get("bus_zone").getValue());
		BusZone busZone = busZoneService.getBusZoneById(busZoneId);
		if (busZone!= null){
			equipmentMap.put("bus_zone", busZone.getName());
		}else{
			equipmentMap.put("bus_zone", "undefined");
		}
		
		//bus_data_area
		//equipmentMap.put("bus_data_area_info", instance.get("bus_data_area").getValue());
		//entity_data_area
//		String[] entityUris = instance.get("entity_data_area").getValue().split("/");
//		logger.info(entityUris.length);
//		StringBuffer entityNames = new StringBuffer();
//		for (String uri: entityUris){
//			DomainEntity domainEntity = domainEntityService.getDomainEntityByUri(uri);
//			entityNames.append(domainEntity.getName()).append("/");
		//}
		//equipmentMap.put("entity_data_areas_info", entityNames.toString());
		//equipment_number
		equipmentMap.put("equipment_number_info", instance.get("equipment_number").getValue());
		
		
		
		//read_init_method
		//InterfaceMethod readInitMethod = interfaceMethodService.getInterfaceMethodById(
		//		new Long(instance.get("read_bus_init_method").getValue()) );
		String readInitMethodName = getMethodDisplayMessage(instance.get("read_bus_init_method"));
		equipmentMap.put("read_bus_init_method_info", readInitMethodName);
		String readProcessingMethodName = getMethodDisplayMessage(instance.get("read_bus_processing_method"));
		equipmentMap.put("read_bus_processing_method_info", readProcessingMethodName);
		String writeInitMethodName = getMethodDisplayMessage(instance.get("write_bus_init_method"));
		equipmentMap.put("write_bus_init_method_info", writeInitMethodName);
		String writeProcessingMethodName = getMethodDisplayMessage(instance.get("write_bus_processing_method"));
		equipmentMap.put("write_bus_processing_method_info", writeProcessingMethodName);
		
		//read_processing_method
//		InterfaceMethod readProcessingMethod = interfaceMethodService.getInterfaceMethodById(
//				new Long(instance.get("read_bus_processing_method").getValue()) );
//		if (readProcessingMethod == null)
//			equipmentMap.put("read_bus_processing_method_info", "undefined");
//		else 
//			equipmentMap.put("read_bus_processing_method_info", readProcessingMethod.getMethodSigniture());
//		
//		//equipmentMap.put("read_frequency_info", instance.get("read_frequency").getValue());
//		
//		//write_init_method
//		InterfaceMethod writeInitMethod = interfaceMethodService.getInterfaceMethodById(
//				new Long(instance.get("write_bus_init_method").getValue()) );
//		if (writeInitMethod == null)
//			equipmentMap.put("write_bus_init_method_info", "undefined");
//		else 
//			equipmentMap.put("write_bus_init_method_info", writeInitMethod.getMethodSigniture());
//		
//		//write_processing_method
//		InterfaceMethod writeProcessingMethod = interfaceMethodService.getInterfaceMethodById(
//				new Long(instance.get("write_bus_processing_method").getValue()) );
//		if (writeProcessingMethod == null)
//			equipmentMap.put("write_bus_processing_method_info", "undefined");
//		else 
//			equipmentMap.put("write_bus_processing_method_info", writeProcessingMethod.getMethodSigniture());
		
		//equipmentMap.put("write_bus_processing_method_info", writeMethod.getMethodSigniture());
		//equipmentMap.put("write_frequency_info", instance.get("write_frequency").getValue());
		equipmentMap.put("success", "true");
		return equipmentMap;
	}
	
	@ExceptionHandler({IOException.class,DBException.class})
	public ResponseEntity<String> handleIOException(IOException ex) {
	    // prepare responseEntity
		HttpHeaders headers = new HttpHeaders();  
        headers.setContentType(MediaType.TEXT_PLAIN);
		ResponseEntity<String> responseEntity =new ResponseEntity<String>("The server has some errors,please try later!", headers,HttpStatus.OK);
	    return responseEntity;
	}
	
	//private void toURL(S)
	
	/** 
	 * 根据method property的内容返回函数组件的函数及其对应的组件的名称
	 */
	private String getMethodDisplayMessage(Property p){
		String value = p.getValue();
		if (value== null || "".equals(value) || !value.contains("=")){
			return "undefined";
		}
		String[] link = value.split("=");
		InterfaceMethod method = interfaceMethodService
				.getInterfaceMethodById(Long.parseLong(link[0]));
		
		MethodComponent methodComponent = methodComponentService
				.getMethodComponentByUri(link[1]);
		
		if (method == null || methodComponent == null)
			return "undefined";
		String fullName = method.getMethodSigniture() + "->" + methodComponent.getName();
		return fullName;
		
	}
	
	private String toURL(String type, long projectId){
		StringBuilder url = new StringBuilder("redirect:/");
		url.append(type).append("/").append(projectId).append("/design_pattern_component/BUS/edit");
		return url.toString();
	}
	
}



